<template>
  <el-card class="box-card">
    <el-form ref="from" label-width="80px" :model="sku" :rules="rules">
      <el-form-item label="SPU名称">
        <span>{{ spu.spuName }}</span>
      </el-form-item>

      <el-form-item label="SKU名称" prop="skuName">
        <el-input v-model="sku.skuName" placeholder="请输入SKU名称" />
      </el-form-item>

      <el-form-item label="SKU价格" prop="price">
        <el-input-number
          v-model="sku.price"
          controls-position="right"
          :min="0"
          placeholder="请输入SKU价格"
        />
      </el-form-item>

      <el-form-item label="SKU重量" prop="weight">
        <el-input-number
          v-model="sku.weight"
          controls-position="right"
          :min="0"
          placeholder="请输入SKU重量"
        />
      </el-form-item>

      <el-form-item label="SKU描述" prop="skuDesc">
        <el-input
          v-model="sku.skuDesc"
          type="textarea"
          placeholder="请输入SKU描述"
        />
      </el-form-item>

      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row>
          <el-col
            v-for="(attr, index) in attrList"
            :key="attr.id"
            :xs="24"
            :md="12"
            :lg="8"
            :xl="6"
          >
            <el-form-item :label="attr.attrName" label-width="100px">
              <el-select
                v-model="sku.skuAttrValueList[index]"
                placeholder="请选择平台属性"
              >
                <el-option
                  v-for="vName in attr.attrValueList"
                  :key="vName.id"
                  :label="vName.valueName"
                  :value="
                    `${attr.id}:${attr.attrName}:${vName.id}:${vName.valueName}`
                  "
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row>
          <el-col
            v-for="(salName, index) in spuSaleAttrList"
            :key="salName.id"
            :xs="24"
            :md="12"
            :lg="8"
            :xl="6"
          >
            <el-form-item :label="salName.saleAttrName">
              <el-select
                v-model="sku.skuSaleAttrValueList[index]"
                placeholder="请选择销售属性"
              >
                <el-option
                  v-for="val in salName.spuSaleAttrValueList"
                  :key="val.id"
                  :label="val.saleAttrValueName"
                  :value="
                    `${salName.id}:${salName.saleAttrName}:${val.id}:${val.saleAttrValueName}`
                  "
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="SKU图片" prop="skuImageList">
        <el-table
          :data="spuImageList"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img class="save-sku-img" :src="row.imgUrl" :alt="row.imgName">
            </template>
          </el-table-column>
          <el-table-column prop="imgName" label="名称" />
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button
                v-if="row.isDefault === '1'"
                type="success"
                size="mini"
                disabled
              >
                默认图片
              </el-button>
              <el-button
                v-else
                type="primary"
                size="mini"
                @click="setSkuDefaultImg(row)"
              >设置默认图片</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">确认</el-button>
        <el-button @click="$emit('isShowSpu', 1)">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { reqGetAttrList } from '@/api/product/attr'
import { reqGetSpuSaleAttrList, reqGetSpuImageList } from '@/api/product/spu'
import { reqSaveSku } from '@/api/product/sku'
import { mapState } from 'vuex'
export default {
  name: 'SaveSku',
  props: {
    spu: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    function skuImageListValidator(rule, value, callback) {
      if (!value.length) {
        callback('至少选中一张图片')
        return
      }
      if (!value.some(img => img.isDefault === '1')) {
        callback('必须设置并选中默认图片')
        return
      }
      callback()
    }
    function skuAttrValueListValidator(rule, value, callback) {
      if (!value.length) {
        callback('必须选中一个平台属性')
        return
      }
      callback()
    }
    function skuSaleAttrValueListValidator(rule, value, callback) {
      if (!value.length) {
        callback('必须选中一个销售属性')
        return
      }
      callback()
    }
    return {
      attrList: [],
      spuSaleAttrList: [],
      spuImageList: [],
      sku: {
        // 名称
        skuName: '',
        // 价格
        price: 0,
        // 重量
        weight: 0,
        // 描述
        skuDesc: '',
        // 平台属性列表
        skuAttrValueList: [
          // {
          //   attrId: 0,
          //   attrName: 'string',
          //   valueId: 0,
          //   valueName: 'string'
          // }
        ],
        // 销售属性列表
        skuSaleAttrValueList: [
          // {
          //   saleAttrId: 0,
          //   saleAttrName: 'string',
          //   saleAttrValueId: 0,
          //   saleAttrValueName: 'string',
          // }
        ],
        // 默认图片地址
        // skuDefaultImg: '',
        // 图片列表
        skuImageList: [
          // {
          //   imgName: 'string',
          //   imgUrl: 'string',
          //   isDefault: 'string'
          // }
        ]
      },
      rules: {
        skuName: [
          { required: true, message: '请输入SKU名称', trigger: 'blur' }
        ],
        // 价格
        price: [{ required: true, message: '请输入SKU价格', trigger: 'blur' }],
        // 重量
        weight: [{ required: true, message: '请输入SKU重量', trigger: 'blur' }],
        // 描述
        skuDesc: [
          { required: true, message: '请输入SKU描述', trigger: 'blur' }
        ],
        // 平台属性列表
        skuAttrValueList: [
          { required: true, validator: skuAttrValueListValidator }
        ],
        // 销售属性列表
        skuSaleAttrValueList: [
          { required: true, validator: skuSaleAttrValueListValidator }
        ],
        // 图片列表
        skuImageList: [{ required: true, validator: skuImageListValidator }]
      }
    }
  },
  computed: {
    ...mapState('category', ['category1Id', 'category2Id', 'category3Id'])
  },
  async mounted() {
    const {
      category1Id,
      category2Id,
      category3Id,
      spu: { id }
    } = this
    const [
      attrListResponse,
      spuSaleAttrListResponse,
      spuImageListResponse
    ] = await Promise.allSettled([
      reqGetAttrList({
        category1Id,
        category2Id,
        category3Id
      }),
      reqGetSpuSaleAttrList(id),
      reqGetSpuImageList(id)
    ])

    if (attrListResponse.status === 'fulfilled') {
      this.attrList = attrListResponse.value.data
    } else {
      this.$message({
        type: 'error',
        message: '获取平台属性列表失败'
      })
    }

    if (spuSaleAttrListResponse.status === 'fulfilled') {
      this.spuSaleAttrList = spuSaleAttrListResponse.value.data
    } else {
      this.$message({
        type: 'error',
        message: '获取销售属性列表失败'
      })
    }

    if (spuImageListResponse.status === 'fulfilled') {
      this.spuImageList = spuImageListResponse.value.data
    } else {
      this.$message({
        type: 'error',
        message: '获取SPU图片列表失败'
      })
    }
  },
  methods: {
    // 提交表单
    submitForm() {
      this.$refs.from.validate(async valid => {
        if (valid) {
          // 收集数据
          const {
            skuName,
            price,
            weight,
            skuDesc,
            skuAttrValueList,
            skuSaleAttrValueList,
            skuImageList
          } = this.sku
          const { category3Id } = this
          const { id } = this.spu
          const skuDefaultImg = skuImageList.find(img => img.isDefault === '1')
            .imgUrl
          // 发请求
          await reqSaveSku({
            skuName,
            price,
            weight,
            skuDesc,
            skuDefaultImg,
            category3Id,
            spuId: id,
            skuImageList,
            skuAttrValueList: skuAttrValueList.filter(Boolean).map(val => {
              const [attrId, attName, valueId, valueName] = val.split(':')
              return {
                attrId,
                attName,
                valueId,
                valueName
              }
            }),
            skuSaleAttrValueList: skuSaleAttrValueList
              .filter(Boolean)
              .map(val => {
                const [
                  saleAttrId,
                  saleAttrName,
                  saleAttrValueId,
                  saleAttrValueName
                ] = val.split(':')
                return {
                  saleAttrId,
                  saleAttrName,
                  saleAttrValueId,
                  saleAttrValueName
                }
              })
          })
          this.$emit('isShowSpu', 1)
          this.$message({
            type: 'success',
            message: '添加SKU成功'
          })
        }
      })
    },
    // 设置默认图片
    setSkuDefaultImg(row) {
      this.spuImageList.forEach(imgObj => {
        this.$set(imgObj, 'isDefault', '0')
      })
      this.$set(row, 'isDefault', '1')
      // row.isDefault === 1
      this.$refs.from.validateField('skuImageList', valid => {
        console.log(valid)
      })
    },
    // 选择图片时触发的回调
    handleSelectionChange(val) {
      this.sku.skuImageList = val
    }
  }
}
</script>

<style lang="sass" scoped>
.save-sku-img
  width: 150px
  height: 150px
</style>
